"use strict";

/// <reference path="../../../../../global.d.ts" />

/* global $ backVar layer */

// 回填各个小标签
function writeBackXiaoleiTag() {
  layer.msg("加载中", {
    icon: 16,
    shade: 0.01
  });
  if (backVar.dalei !== "") {
    $("#dalei").val(backVar.dalei);
    $("#dalei").change();
  }

  var _loop = function _loop(e) {
    // 这是非常脏的hack方式……因为执行这个语句的时候tageditor没有建立，所以就延迟0.5喵来执行这个事情
    console.dir(backVar.tag.check);
    setTimeout(function _this() {
      var value = $("input[name='check[]'][value='" + e + "']");
      if (value.length === 0) {
        console.log("try again");
        setTimeout(_this, 100);
      } else {
        /* 得到小类的显示值，用于直接push */
        var _value = value.attr("id");
        console.log("done: " + _value);
        $("#xiaolei_tag_list").tagEditor("addTag", _value, true);
      }
    }, 0);
  };

  var _iteratorNormalCompletion = true;
  var _didIteratorError = false;
  var _iteratorError = undefined;

  try {
    for (
      var _iterator = backVar.tag.check[Symbol.iterator](), _step;
      !(_iteratorNormalCompletion = (_step = _iterator.next()).done);
      _iteratorNormalCompletion = true
    ) {
      var e = _step.value;

      _loop(e);
    }
  } catch (err) {
    _didIteratorError = true;
    _iteratorError = err;
  } finally {
    try {
      if (!_iteratorNormalCompletion && _iterator.return) {
        _iterator.return();
      }
    } finally {
      if (_didIteratorError) {
        throw _iteratorError;
      }
    }
  }
}
function writeBackTag() {
  // i 就是tag中的每一项，实际意义代表每一个tag类别
  var _iteratorNormalCompletion2 = true;
  var _didIteratorError2 = false;
  var _iteratorError2 = undefined;

  try {
    for (
      var _iterator2 = Object.keys(backVar.tag)[Symbol.iterator](), _step2;
      !(_iteratorNormalCompletion2 = (_step2 = _iterator2.next()).done);
      _iteratorNormalCompletion2 = true
    ) {
      var i = _step2.value;

      console.log(i);
      if (i !== "check") {
        var _loop2 = function _loop2(e) {
          // 获取前缀，例子：check_shouru -> shouru
          var qianzui = i.replace(/check_/, "");
          // 这是非常脏的hack方式……因为执行这个语句的时候tageditor没有建立，所以就延迟0.5喵来执行这个事情
          setTimeout(function() {
            $("#" + qianzui + "_tag_list").tagEditor("addTag", e, true);
          }, 500);
        };

        var _iteratorNormalCompletion3 = true;
        var _didIteratorError3 = false;
        var _iteratorError3 = undefined;

        try {
          for (
            var _iterator3 = backVar.tag[i][Symbol.iterator](), _step3;
            !(_iteratorNormalCompletion3 = (_step3 = _iterator3.next()).done);
            _iteratorNormalCompletion3 = true
          ) {
            var e = _step3.value;

            _loop2(e);
          }
        } catch (err) {
          _didIteratorError3 = true;
          _iteratorError3 = err;
        } finally {
          try {
            if (!_iteratorNormalCompletion3 && _iterator3.return) {
              _iterator3.return();
            }
          } finally {
            if (_didIteratorError3) {
              throw _iteratorError3;
            }
          }
        }
      } else if (i === "check") {
        writeBackXiaoleiTag();
      }
    }
  } catch (err) {
    _didIteratorError2 = true;
    _iteratorError2 = err;
  } finally {
    try {
      if (!_iteratorNormalCompletion2 && _iterator2.return) {
        _iterator2.return();
      }
    } finally {
      if (_didIteratorError2) {
        throw _iteratorError2;
      }
    }
  }
}
// 回填各个要求
function writeBackxiangxi() {
  var _iteratorNormalCompletion4 = true;
  var _didIteratorError4 = false;
  var _iteratorError4 = undefined;

  try {
    for (
      var _iterator4 = Object.keys(backVar.yaoqiu)[Symbol.iterator](), _step4;
      !(_iteratorNormalCompletion4 = (_step4 = _iterator4.next()).done);
      _iteratorNormalCompletion4 = true
    ) {
      var i = _step4.value;

      // console.log(backVar.yaoqiu[i])
      if (i === "fangkuan_fangshi_se" || i === "zhengxin_xianshi") {
        $("#" + i).val(backVar.yaoqiu[i]);
      } else if (i === "shangmen") {
        var _iteratorNormalCompletion5 = true;
        var _didIteratorError5 = false;
        var _iteratorError5 = undefined;

        try {
          for (
            var _iterator5 = backVar.yaoqiu[i][Symbol.iterator](), _step5;
            !(_iteratorNormalCompletion5 = (_step5 = _iterator5.next()).done);
            _iteratorNormalCompletion5 = true
          ) {
            var j = _step5.value;

            $("input[name='shangmen[]'][value='" + j + "']").click();
          }
        } catch (err) {
          _didIteratorError5 = true;
          _iteratorError5 = err;
        } finally {
          try {
            if (!_iteratorNormalCompletion5 && _iterator5.return) {
              _iterator5.return();
            }
          } finally {
            if (_didIteratorError5) {
              throw _iteratorError5;
            }
          }
        }
      } else if (i === "jinzhi") {
        $(".hangye_ban.sec_box input").each(function(index, item) {
          $(item).prop("checked", false);
        });
        // 公交司机,美容,美发,快递公司
        var rawValue = ("" + backVar.yaoqiu[i]).split(",");
        if (rawValue.length === 0) continue;
        var _iteratorNormalCompletion6 = true;
        var _didIteratorError6 = false;
        var _iteratorError6 = undefined;

        try {
          for (
            var _iterator6 = rawValue[Symbol.iterator](), _step6;
            !(_iteratorNormalCompletion6 = (_step6 = _iterator6.next()).done);
            _iteratorNormalCompletion6 = true
          ) {
            var value = _step6.value;

            $(".hangye_ban input[value='" + value + "']")
              .prop("checked", true)
              .change();
          }
        } catch (err) {
          _didIteratorError6 = true;
          _iteratorError6 = err;
        } finally {
          try {
            if (!_iteratorNormalCompletion6 && _iterator6.return) {
              _iterator6.return();
            }
          } finally {
            if (_didIteratorError6) {
              throw _iteratorError6;
            }
          }
        }
      } else if (
        i === "danwei" ||
        i === "peiou" ||
        i === "zhixi" ||
        i === "qingsu" ||
        i === "tongshi" ||
        i === "pengyou"
      ) {
        if (backVar.yaoqiu[i] === "") {
        } else if (
          $("input[name='" + i + "'][value='" + backVar.yaoqiu[i] + "']").val()
        ) {
          $(
            "input[name='" + i + "'][value='" + backVar.yaoqiu[i] + "']"
          ).click();
        } else {
          $("input[name='" + i + "_zidingyi']").click();
          $("input[name='" + i + "_zidingyi']").val(backVar.yaoqiu[i]);
          $("input[name='" + i + "_zidingyi']").change();
        }
      } else
        $("input[name='" + i + "'][value='" + backVar.yaoqiu[i] + "']").click();
    }
  } catch (err) {
    _didIteratorError4 = true;
    _iteratorError4 = err;
  } finally {
    try {
      if (!_iteratorNormalCompletion4 && _iterator4.return) {
        _iterator4.return();
      }
    } finally {
      if (_didIteratorError4) {
        throw _iteratorError4;
      }
    }
  }
}

/** 回填diy表单 */
function writeBackDIYForm(data) {
  var id = data.m_group;
  var value = data.m_value;
  var formID = data.group;
  var dataBackURL = String($("#get_free_form_data").val());
  try {
    var _backVar = JSON.parse(window.backVar.tag_check_ori).cpclass;
  } catch (err) {
    console.log("回填数据丢失");
  }

  function genDIYNumberLine(Obj, uniID, DIYFormDataId) {
    var resData = {
      mainData: "",
      altData: ""
    };
    $.ajax(dataBackURL, {
      method: "POST",
      data: { md_id: DIYFormDataId },
      async: false
    })
      .done(function(data) {
        if (data.code !== "1") {
          console.log(
            "\u4E0D\u80FD\u6B63\u786E\u8BF7\u6C42\u6570\u636E\uFF0C\u4F4D\u4E8E\uFF1AgenDIYNumberLine(),message\u4E3A\uFF1A" +
              data.message
          );
        } else {
          var res = data.data;
          resData.mainData = res.maindata;
          resData.altData = res.altdata;
        }
      })
      .fail(function() {
        throw new Error("通信失败，请检查网络，来自：不能正确请求数据，位于：genDIYNumberLine()");
      });
    return ('\n    <div class="input_wrap number_input" id=\'hidden_from_backend' +
      uniID +
      '\'>\n      <div class="title"><input type="text" form=\'not_submit\' name="[title]" placeholder="\u540D\u79F0" value=\'' +
      Obj.title +
      "' readonly></div>\n      <!-- \u56FA\u5B9A\u9690\u85CFinput\uFF0C\u7528\u4E8E\u540E\u7AEF\u5206\u8FA8\u8BE5\u884C\u8868\u5355\u7C7B\u578B -->\n      <input type='hidden' name='type' value='1'>\n      <div class=\"alt_data\">\n        <select\n          form = 'not_submit' name=\"[alt_data]\"\n          aria-multiple = 'false'\n          aria-placeholder=\"\u8BF7\u9009\u62E9\u53D6\u503C\u65B9\u5411\"\n        >\n          <option></option>\n          <optgroup label=\"\">\n              <option value=\"\u5927\u4E8E\" " +
      (resData.altData === "大于" ? "selected" : "") +
      '>\u5927\u4E8E</option>\n              <option value="\u5927\u4E8E\u7B49\u4E8E" ' +
      (resData.altData === "大于等于" ? "selected" : "") +
      '>\u5927\u4E8E\u7B49\u4E8E</option>\n              <option value="\u5C0F\u4E8E" ' +
      (resData.altData === "小于" ? "selected" : "") +
      '>\u5C0F\u4E8E</option>\n              <option value="\u5C0F\u4E8E\u7B49\u4E8E" ' +
      (resData.altData === "小于等于" ? "selected" : "") +
      '>\u5C0F\u4E8E\u7B49\u4E8E</option>\n              <option value="\u7B49\u4E8E" ' +
      (resData.altData === "等于" ? "selected" : "") +
      '>\u7B49\u4E8E</option>\n            </optgroup>\n        </select>\n      </div>\n      <div class="main_data">\n        <input type="text" form=\'not_submit\' name="[main_data]" placeholder="\u6570\u503C" value=\'' +
      resData.mainData +
      "'>\n      </div>\n    </div>\n    <script id='tempmlScript" +
      uniID +
      "'>\n      $('#hidden_from_backend" +
      uniID +
      " .alt_data select').select2({\n        placeholder: '\u8BF7\u9009\u62E9\u53D6\u503C\u65B9\u5411',\n        tags: false,\n        multiple: false,\n        width: 'element'\n      }).val('" +
      resData.altData +
      "').trigger('change')\n      setTimeout(()=>{$('#tempmlScript" +
      uniID +
      "').remove()}, 0)\n    </script>\n    ").trim();
  }
  function genDIYSLine(Obj, uniID, DIYFormDataId) {
    var resData = {
      mainData: "",
      altData: ""
    };
    $.ajax(dataBackURL, {
      method: "POST",
      data: { md_id: DIYFormDataId },
      async: false
    })
      .done(function(data) {
        if (data.code !== "1") {
          console.log(
            "\u4E0D\u80FD\u6B63\u786E\u8BF7\u6C42\u6570\u636E\uFF0C\u4F4D\u4E8E\uFF1AgenDIYSLine(),message\u4E3A\uFF1A" +
              data.message
          );
        } else {
          var res = data.data;
          resData.mainData = res.maindata;
          resData.altData = res.altdata;
        }
      })
      .fail(function() {
        throw new Error("通信失败，请检查网络，来自：不能正确请求数据，位于：genDIYSLine()");
      });

    var options = "";
    var templ = ('\n    <div class="input_wrap single_select" id=\'hidden_from_backend' +
      uniID +
      '\'>\n      <div class="title"><input type="text" form=\'not_submit\' name="[title]" placeholder="\u540D\u79F0" value=\'' +
      Obj.title +
      "' readonly></div>\n      <!-- \u56FA\u5B9A\u9690\u85CFinput\uFF0C\u7528\u4E8E\u540E\u7AEF\u5206\u8FA8\u8BE5\u884C\u8868\u5355\u7C7B\u578B -->\n      <input type='hidden' name='type' value='2'>\n      <div class=\"alt_data\">\n        <select\n          form = 'not_submit' name=\"[alt_data]\"\n        >\n          <optgroup label=\"\u6682\u65E0\u9009\u9879\"></optgroup>\n        </select>\n      </div>\n      <div class=\"main_data\">\n          <select\n            form = 'not_submit' name=\"[main_data]\"\n          >\n            <option inori-id='here-inori'></option>\n          </select>\n      </div>\n    </div>\n    <script id='tempmlScript" +
      uniID +
      "'>\n      $('#hidden_from_backend" +
      uniID +
      " .alt_data select').select2({\n        placeholder: '\u65E0\u9700\u9009\u62E9',\n        tags: false,\n        multiple: false,\n        width: 'element'\n      })\n      $('#hidden_from_backend" +
      uniID +
      " .main_data select').select2({\n        placeholder: '\u8BF7\u9009\u62E9\u5177\u4F53\u9009\u9879',\n        tags: false,\n        multiple: false,\n        width: 'element'\n      }).val(null).trigger('change')\n      setTimeout(()=>{$('#tempmlScript" +
      uniID +
      "').remove()}, 0)\n    </script>\n    ").trim();
    var flag = false;
    $.each(Obj.main_data, function(index, opn) {
      /* 其实 `text === value` */
      if (resData.mainData === opn.key) {
        options +=
          "<option value='" +
          opn.value +
          "' inori-data='" +
          opn.key +
          "' selected>" +
          opn.text +
          "</option>";
        flag = true;
      } else {
        options +=
          "<option value='" +
          opn.value +
          "' inori-data='" +
          opn.key +
          "'>" +
          opn.text +
          "</option>";
      }
    });
    if (flag) templ = templ.replace(/\.val\(null\)\.trigger\('change'\)/, "");
    return templ.replace("<option inori-id='here-inori'></option>", options);
  }
  function genDIYMLine(Obj, uniID, DIYFormDataId) {
    var resData = {
      mainData: {
        id: [],
        value: []
      },
      altData: ""
    };
    $.ajax(dataBackURL, {
      method: "POST",
      data: { md_id: DIYFormDataId },
      async: false
    })
      .done(function(data) {
        if (data.code !== "1") {
          console.log(
            "\u4E0D\u80FD\u6B63\u786E\u8BF7\u6C42\u6570\u636E\uFF0C\u4F4D\u4E8E\uFF1AgenDIYMLine(),message\u4E3A\uFF1A" +
              data.message
          );
        } else {
          var res = data.data;
          resData.mainData = {
            id: String(res.maindata).split(","),
            value: []
          };
          resData.altData = res.altdata;
        }
      })
      .fail(function() {
        throw new Error("通信失败，请检查网络，来自：不能正确请求数据，位于：genDIYMLine()");
      });

    var options = '<optgroup label="">';
    var templ =
      '\n    <div class="input_wrap multiple_select" id=\'hidden_from_backend' +
      uniID +
      '\'>\n      <div class="title"><input type="text" form=\'not_submit\' name="[title]" placeholder="\u540D\u79F0" value=\'' +
      Obj.title +
      "' readonly></div>\n      <!-- \u56FA\u5B9A\u9690\u85CFinput\uFF0C\u7528\u4E8E\u540E\u7AEF\u5206\u8FA8\u8BE5\u884C\u8868\u5355\u7C7B\u578B -->\n      <input type='hidden' name='type' value='3'>\n      <div class=\"alt_data\">\n        <select\n          form = 'not_submit' name=\"[alt_data]\"\n        >\n          <optgroup label=\"\">\n              <option value=\"\u540C\u65F6\u7B26\u5408\" " +
      (resData.altData === "同时符合" ? "selected" : "") +
      '>\u540C\u65F6\u7B26\u5408</option>\n              <option value="\u4EFB\u610F\u7B26\u5408" ' +
      (resData.altData === "任意符合" ? "selected" : "") +
      ">\u4EFB\u610F\u7B26\u5408</option>\n            </optgroup>\n        </select>\n      </div>\n      <div class=\"main_data\">\n          <select\n            form = 'not_submit' name=\"[main_data][]\"\n          >\n          <option inori-id='here-inori'></option>\n          </select>\n      </div>\n    </div>\n    <script id='tempmlScript" +
      uniID +
      "'>\n      $('#hidden_from_backend" +
      uniID +
      " .alt_data select').select2({\n        placeholder: '\u8BF7\u9009\u62E9\u5177\u4F53\u9009\u9879\uFF08\u5FC5\u586B\uFF09',\n        tags: false,\n        multiple: false,\n        width: 'element'\n      })\n      $('#hidden_from_backend" +
      uniID +
      " .main_data select').select2({\n        placeholder: '\u8BF7\u9009\u62E9\u5177\u4F53\u9009\u9879\uFF08\u5FC5\u586B\uFF09',\n        // tags: true,\n        multiple: true,\n        tokenSeparators: [',', ' '],\n        width: 'element',\n        closeOnSelect: false\n      }).inori_replace_placeholder\n      setTimeout(()=>{$('#tempmlScript" +
      uniID +
      "').remove()}, 0)\n    </script>\n    ";
    $.each(Obj.main_data, function(index, opn) {
      /* 其实 `text === value` */
      options +=
        "<option value='" +
        opn.value +
        "' inori-data='" +
        opn.key +
        "'>" +
        opn.text +
        "</option>";
      // 组成val值
      if (resData.mainData.id.indexOf(opn.key) > -1)
        resData.mainData.value.push('"' + opn.text + '"');
    });
    options += "</optgroup>";
    return templ
      .replace("<option inori-id='here-inori'></option>", options)
      .replace(
        /inori_replace_placeholder/,
        "val([" + resData.mainData.value + "]).trigger('change')"
      );
  }
  function genDIYForm(tagMessage, formID, formData) {
    var DIYFormDataId = "";
    var templWrap = ('\n    <div class="hdden_free_wrap_' +
      tagMessage.id +
      ' hdden_free_wrap">\n      <input type="hidden" name="hidden_free[1][group_id]" value="' +
      formID +
      '">\n      <div style="width:100%;height:1px;clear:both;"></div>\n      <div class = "wrap_title">\u5C0F\u7C7B\uFF1A' +
      tagMessage.value +
      '</div>\n      <input type="hidden" class=\'hiddenLineCounter\' name="lineCounter" value="3" form=\'not_submit\'>\n      <input type="hidden" name="hidden_free[1][id]" value="' +
      tagMessage.id +
      '">\n      <input type="hidden" name="hidden_free[1][value]" value="' +
      tagMessage.value +
      '">\n\n      <!-- \u8868\u5355\u63D2\u5165 -->\n\n      <!-- \u6700\u540E\u4E00\u4E2A\u5143\u7D20\u5FC5\u987B\u662Fdiv\uFF0C\u63D2\u5165\u5143\u7D20\u5B9A\u4F4D\u4E3A\u6700\u540E\u4E00\u4E2Adiv\u4E4B\u524D -->\n      <div class="button">\n        \u9875\u9762\u63D0\u4EA4\u524D\u5FC5\u987B\u5148\u63D0\u4EA4\u672C\u533A\u57DF\uFF01\n        <br>\n        <button onclick=\'postThisHiddenLine(this, event, "second")\'>\u4FDD\u5B58</button>\n      </div>\n    </div>\n    ').trim();
    var templWrapReplace = "";
    var switchObj = {
      1: genDIYNumberLine,
      2: genDIYSLine,
      3: genDIYMLine
    };
    $.each(formData, function(index, Obj) {
      try {
        var tempObj = JSON.parse(backVar.tag_check_ori).cpclass;
        var _iteratorNormalCompletion7 = true;
        var _didIteratorError7 = false;
        var _iteratorError7 = undefined;

        try {
          for (
            var _iterator7 = tempObj.keys()[Symbol.iterator](), _step7;
            !(_iteratorNormalCompletion7 = (_step7 = _iterator7.next()).done);
            _iteratorNormalCompletion7 = true
          ) {
            var e = _step7.value;
            var _iteratorNormalCompletion8 = true;
            var _didIteratorError8 = false;
            var _iteratorError8 = undefined;

            try {
              for (
                var _iterator8 = tempObj[e].my_data[Symbol.iterator](), _step8;
                !(_iteratorNormalCompletion8 = (_step8 = _iterator8.next())
                  .done);
                _iteratorNormalCompletion8 = true
              ) {
                var myDataItem = _step8.value;

                if (myDataItem.m_group === tagMessage.id + "_" + index) {
                  DIYFormDataId = myDataItem.md_id;
                }
              }
            } catch (err) {
              _didIteratorError8 = true;
              _iteratorError8 = err;
            } finally {
              try {
                if (!_iteratorNormalCompletion8 && _iterator8.return) {
                  _iterator8.return();
                }
              } finally {
                if (_didIteratorError8) {
                  throw _iteratorError8;
                }
              }
            }
          }
        } catch (err) {
          _didIteratorError7 = true;
          _iteratorError7 = err;
        } finally {
          try {
            if (!_iteratorNormalCompletion7 && _iterator7.return) {
              _iterator7.return();
            }
          } finally {
            if (_didIteratorError7) {
              throw _iteratorError7;
            }
          }
        }
      } catch (err) {
        console.log(err);
        console.log("回填数据失败，没有数据变量");
      }
      templWrapReplace += switchObj[Obj.input_type](
        Obj,
        formID + "_" + tagMessage.id + "_" + index,
        DIYFormDataId
      );
    });
    templWrap = templWrap.replace(
      "<!-- \u8868\u5355\u63D2\u5165 -->",
      templWrapReplace
    );
    $("#hdden_free_form_wrap").append(templWrap);
    console.log("done");
    layer.closeAll("loading");
  }

  genDIYForm({ id: id, value: value }, formID, data.formData);
}
